﻿using System.Drawing;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace aboveUHSReader
{
  internal class UHSNode : TreeNode
  {
    private string m_content;

    public UHSNode(string subject)
    {
      Subject = subject;
      if (Subject == "Link") ForeColor = Color.Blue;
    }

    public string Subject { get; private set; }
    public bool Proportional { get; private set; }

    public virtual string Content
    {
      get { return m_content; }
      set
      {
        if (Subject == "TextData")
        {
          Text = @"-->";
          m_content = value;
          if (!Proportional)
            Proportional = m_content.Contains("#p-") || m_content.Contains("#p+");
          if (Proportional)
          {
            while (m_content.IndexOf("#p-") != -1)
              m_content = m_content.Remove(m_content.IndexOf("#p-"), 3);
            while (m_content.IndexOf("#p+") != -1)
              m_content = m_content.Remove(m_content.IndexOf("#p+"), 3);
          }
        }
        else
        {
          m_content = value;
          Text = value;
        }
      }
    }

    public int Id { get; set; }
    public int LinkTarget { get; set; }

    public byte[] ContentToByteArray
    {
      get
      {
        var bytes = new byte[Content.Length];
        for (int c = 0; c < Content.Length; ++c)
          bytes[c] = (byte) Content[c];
        return bytes;
      }
    }

    public TreeNode Copy
    {
      get { return new UHSNode(Subject) {Content = Content}; }
    }

    public void Add(UHSNode node)
    {
      if (node.Subject == "TextData" ||
          Subject == "Version" ||
          Subject == "Incentive" ||
          Subject == "Info")
      {
        Subject = "TextData";
        m_content = node.Content;
        if (node.Proportional)
          Proportional = node.Proportional;
      }
      else
        Nodes.Add(node);
    }

    public bool Contains(string searchString)
    {
      var regex = new Regex(searchString, RegexOptions.Singleline | RegexOptions.IgnoreCase);
      return regex.Match(Content).Success;
    }
  }
}